
/*
    订阅队列消息客户端
*/

#include "mq_connection.hpp"

//订阅者处理消息的回调函数
void callback(const xgmq::Channel::ptr& channel, const std::string &consume_tag, 
                const xgmq::basicProperties *bp, const std::string& body)
{
    std::cout<<consume_tag<<"消费了消息:"<<body<<std::endl;
    //对消息进行确认
    channel->basicAck(bp->id());
}

//通过命令行参数获取要绑定的队列名称
int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        std::cout<<"usage: ./consume_client queuename\n";
        return -1;
    }
    //1.声明一个异步工作线程
    xgmq::AsyncWorker::ptr worker=std::make_shared<xgmq::AsyncWorker>();
    //2.实例化连接对象
    xgmq::Connection::ptr con=std::make_shared<xgmq::Connection>("127.0.0.1",8085,worker);
    //3.通过连接创建信道
    xgmq::Channel::ptr channel=con->createChannel();

    //4,接下来的服务通过信道完成
    //声明交换机
    google::protobuf::Map<std::string, std::string> tmp_arg;
    channel->declareExchange("exchange1",xgmq::ExchangeType::FANOUT,true,false,tmp_arg);
    //声明两个队列
    channel->declareQueue("queue1",true,false,false,tmp_arg);
    channel->declareQueue("queue2",true,false,false,tmp_arg);
    //将交换机与队列进行绑定
    channel->queueBind("exchange1","queue1","queue1");
    channel->queueBind("exchange1","queue2","news.music.#");

    auto func=std::bind(callback,channel,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3);
    //订阅队列
    channel->basicConsume("consume1",false,argv[1],func);

    while(1) std::this_thread::sleep_for(std::chrono::seconds(3));
    //关闭信道
    con->closeChannel(channel);
    return 0;
}